package dao

import (
	"database/sql"
	"github.com/pkg/errors"
)

type User struct {
	Id int
	Name string
	Email string
	Psw string
	CreateAt sql.NullTime
	UpdateAt sql.NullTime
}

func UserList() (*[]User, error) {
	var result []User
	rows, err := db.Query("select * from `user`")
	if err != nil {
		return nil, err
	}

	defer rows.Close()

	for rows.Next() {
		var user User
		err = rows.Scan(&user.Id, &user.Name, &user.Email, &user.Psw, &user.CreateAt, &user.UpdateAt)
		if err != nil {
			return nil, err
		}
		result = append(result, user)
	}

	if err = rows.Err(); err != nil {
		return nil, err
	}

	return &result, nil
}

func FindUserByName(name string) (*User, error) {
	var user User
	err := db.QueryRow(
		"select `id`, `name`, `email`, `create_at`, `update_at` from `user` where `name` = ?",
		name,
		).Scan(&user.Id, &user.Name, &user.Email, &user.CreateAt, &user.UpdateAt)
	return &user, errors.Wrap(err, "dao: FindUserByName")
}